define(function(require, exports, module) {
    'use strict';

    var $ = require('jquery');
    var Slider = require('plugins/slider');
    var LazyStream = require('plugins/lazystream');
    var Lazyload = require('plugins/lazyload');
    var io = require('plugins/request');
    var box = require('plugins/box/box');
    var wx = require('plugins/jweixin-1.0.0');
    require('plugins/imgLoading');

    $('.jImg').imgLoading();

    if($('.jSliderImg').length>1){
        var slider = new Slider('#slides', {
            width:640,
            height:222,
            lazyLoad: {
                attr: 'data-url',
                loadingClass: 'img-error'
            },
            play: {
              auto: true,
              interval: 4000,
              swap: true,
              pauseOnHover: true,
              restartDelay: 2500
            },
            callback:{
                start:function(index){
                },
                loaded : function(){
                }
            }
        });
    }else{
        var el = $('.jSliderImg').eq(0);
        var src = el.attr('data-url');
        sliderImgLoad(src,el);
        $('#slides').addClass('ui-slider-one');
    }

    function sliderImgLoad(src,el) {
        if (isImgUrl(src)) {
            var objImg = new Image();
            objImg.src = src;
            if (objImg.complete) {
                el.attr('src',src).removeClass('img-error').removeAttr('data-url');
            } else {
                objImg.onload = function() {
                    el.attr('src',src).removeClass('img-error').removeAttr('data-url');
                };
            }
        }
    }

    function isImgUrl(str) {
        return (/^((https?|ftp|rmtp|mms):)?\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i).test(str);
    }

    /**
     * 商品详情页图片懒加载
     */
    loadGoodsDetail('.show-details');

    function loadGoodsDetail(obj) {
        var $el = $(obj).find('.jGoodsDetails');
        if(!$el.length){
            return false;
        }
        var eGoodsIntro = $('<div>'+$el.val()+'</div>');
        var eImg = eGoodsIntro.find('img');
        eImg.each(function() {
            var $this = $(this), src = $this.attr('src');
            $this.attr('data-url', src);
            $this.removeClass('jImg');
            $this.addClass('jImg img-error');
        });
        $(obj).find('.jGoodsDetaisCnt').html(eGoodsIntro).find('p span')
        .each(function(index, item){
            var css = $(item).css('fontSize').slice(0, $(item).length-3);
            css && $(item).css('font-size', (css*2/46.875)+'rem');
        });
        resetImageLoader();
    }

    var imageLazyLoader = null;

    function resetImageLoader() {
        // Please make sure destroy it firts if not null
        if (imageLazyLoader) {
          imageLazyLoader.destroy();
        }
        imageLazyLoader = new Lazyload('img.jImg', {
          effect: 'fadeIn',
          dataAttribute: 'url',
          load : function(self){
            if($(self).hasClass('img-error')){
                $(self).removeClass('img-error');
            }
          }
        });
        return imageLazyLoader;
    }

    //获取图片大小
    function getSizeByUri(picUri) {
        var size = {};
        var ptn = /_([0-9]+)x([0-9]+).([^.\/_]+)\!([0-9]+)$/;
        var items = ptn.exec(picUri);
        if (items) {
            size.w = parseInt(items[1]);
            size.h = parseInt(items[2]);
            size.size = parseInt(items[4]);
        } else {
            ptn = /_([0-9]+)x([0-9]+).([^.\/_]+)$/;
            items = ptn.exec(picUri);
            if (items) {
                size.w = parseInt(items[1]);
                size.h = parseInt(items[2]);
                size.size = size.w;
            } else {
                size = null;
            }
        }
        return size;
    }

    var delay = (function () {
        var timer = 0;
        return function (callback, time) {
            clearTimeout(timer);
            timer = setTimeout(callback, time);
        };
    })();


    //购买数量
    $('.jMinus').click(function(){
        getPrice('-');
    });

    $('.jPlus').click(function(){
        getPrice('+');
    });

    $('.jBuyNum').on('blur', function(){
        getPrice();
    });

    function getPrice(type){
        var $buyNum = $('.jBuyNum');
        var buyNum = Number($.trim($buyNum.val()));
        var minNum = Number($buyNum.attr('data-min'));
        var maxNum = Number($buyNum.attr('data-max'));
        var reg = /^[0-9]+$/;
        if(type == '-'){
            buyNum--;
        }
        if(type == '+'){
            buyNum++;
        }
        if(buyNum<minNum){
            box.error('最小购买数量为1',{id:'buy-error'});
            return false;
        }
        if(buyNum>maxNum){
            box.error('最大购买数量为'+maxNum,{id:'buy-error'});
            return false;
        }
        $('.jBuyNum').val(buyNum);
        delay(function(){
            io.jsonp('/json/buy-num.php', {number: buyNum}, function(rst){
                $('.jSetPrice').text(rst.data.price);
            }, function(rst){
                box.error(rst.msg);
            });
        },200);
    }

    /* 详情切换 */
    $('.tab-item').click(function(){
        var index = $(this).index();
        $(this).addClass('active').siblings().removeClass('active');
        $('.tab-panel').eq(index).addClass('show-details').show().siblings().removeClass('show-details').hide();
        loadGoodsDetail('.show-details');
    });

    //判断微信浏览器
    function isWeixin() {
        var ua = navigator.userAgent.toLowerCase();
        return /micromessenger/.test(ua);
    }


    /* 微信支付 */
    $('.jPay').click(function(){
        var self = this;
        io.post('url', {}, function(rst){
            if(rst.data.payType == 0){
                window.location.href = "";
            }else{
                var str = $('.jBuySel').html();
                box.confirm(str, {
                    id: '_payPrice',
                    xtype: 'none',
                    ok: {
                        text: '确定',
                        fn: function() {
                            payPrice(self);
                        }
                    },
                    cancel: {
                       text: '取消'
                    }
                });
            }
        }, function(rst){
            box.error(rst.msg);
        }, self);
    });

    /* 支付请求 */
    function payPrice(obj){
        if(!isWeixin()){
            box.error('请使用微信访问支付!');
            return false;
        }
        //发起支付请求需要的参数
        var dataJson = {
            payPrice: $('input[name="payPrice"]').val()
        }   
        io.jsonp(location.href, dataJson, function (rst) {
            var data = rst.data || {};
            /* 支付签名信息初始化配置
            ** 接口数据返回格式
            ** {
                    "error":"0",
                    "msg":"",
                    "data":{
                        "appId":"wx7a31de4ac31595ab",
                        "noncestr":"969pPAYURLaOKlYyY",
                        "signature":"70e18416accdf510b081a77562252d3a68d7b63f",
                        "timestamp":1501236111,
                        "url":null      //用于支付成功后跳转的页面url
                        },
                    "ver":"1.0"
                }
             */
            wx.config({
                debug: false,
                appId: data.appId,
                timestamp: data.timeStamp,
                nonceStr: data.nonceStr,
                signature: data.paySign,
                jsApiList: [
                    'chooseWXPay'
                ]
            });
            wx.ready(function(){
                wx.checkJsApi({
                    jsApiList: ['chooseWXPay'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
                    success: function (res) {
                        /* 支付接口校验成功后调用支付 */
                        if (res.checkResult.chooseWXPay) {
                            wx.chooseWXPay({
                                timestamp: data.timeStamp,
                                nonceStr: data.nonceStr,
                                package: data.package,
                                signType: data.signType, // 注意：新版支付接口使用 MD5 加密
                                paySign: data.paySign,
                                success: function (res) {
                                    window.location.href = data.linkUrl;    //支付成功后回调
                                },
                                cancel: function (res) {
                                    box.tips('支付已取消！');
                                    //取消回调
                                },
                                fail: function (res) {
                                    box.tips('支付失败！');
                                    //失败回调
                                }
                            });
                        } else {
                            box.tips('请将您的微信升级到最新版！');
                        }
                    },
                    fail: function () {
                        box.tips('请将您的微信升级到最新版！');
                    }
                });
            });
        }, function (e) {
            box.error(e.msg);
        });
    }

});
